import { defineStore } from 'pinia'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { useTagsStore } from '@/store/modules/tags'
import { router } from '@/router'
import { notification } from 'ant-design-vue'
import { authAPI } from '@/api/auth'

export const useUserStore = defineStore('user', {
  state: () => {
    return {
      welcome: '早上好',
      userInfo: {},
      roles: [],
    }
  },
  getters: {
    getRoles() {
      return this.roles || []
    },
  },
  actions: {
    async login(userInfo) {
      authAPI.login({ name: userInfo.username }).then((res) => {
        if (res.success) {
          setToken(res.data.token)
          router.push('/')
          notification.success({
            message: '登录成功',
            description: `欢迎回来,${userInfo.username}`,
          })
        } else {
          notification.error({
            message: '登录失败',
            description: res.message,
          })
        }
      })
      // 登录接口 设置token
    },
    // 通过路由拦截判断是否有token，没有token就获取
    getUserInfo(token) {
      return new Promise((resolve, reject) => {
        const token = getToken()
        authAPI
          .getUserInfo({ token })
          .then((res) => {
            if (res.success) {
              const { role, userInfo } = res.data
              this.roles = [role]
              this.userInfo = userInfo
              const roles = [role]
              resolve({ roles })
            } else {
              reject(error)
            }
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    logout() {
      const tagsStore = useTagsStore()
      this.roles = []
      this.userInfo = {}
      removeToken()
      tagsStore.resetTags()
      router.push('/login')
    },
  },
})
